import React, { useState, useEffect } from 'react';
import {
  Form,
  Input,
  Select,
  Button,
  Space,
  Alert,
  Typography,
  Divider,
  Row,
  Col,
  Card,
  Tag,
  message,
  Switch,
  List,
  Tooltip,
  Modal,
  Tabs,
  Empty
} from 'antd';
import {
  SaveOutlined,
  CopyOutlined,
  EyeOutlined,
  PlusOutlined,
  DeleteOutlined,
  QuestionCircleOutlined,
  CodeOutlined,
  FormOutlined,
  SettingOutlined,
  FileTextOutlined
} from '@ant-design/icons';
import MonacoEditor from '@monaco-editor/react';
import './style.css';

const { Title, Text, Paragraph } = Typography;
const { TextArea } = Input;
const { TabPane } = Tabs;

interface TemplateEditorProps {
  template?: any;
  onSave: (template: any) => void;
  onCancel: () => void;
}

interface TemplateVariable {
  name: string;
  description: string;
  type: 'text' | 'number' | 'date' | 'select' | 'textarea';
  required: boolean;
  defaultValue?: string;
  options?: string[];
  placeholder?: string;
}

const TEMPLATE_CATEGORIES = [
  { value: 'news', label: '新闻报道' },
  { value: 'product', label: '产品描述' },
  { value: 'tech', label: '技术文档' },
  { value: 'email', label: '邮件模板' },
  { value: 'social', label: '社交媒体' },
  { value: 'blog', label: '博客文章' },
  { value: 'marketing', label: '营销文案' },
  { value: 'academic', label: '学术论文' },
  { value: 'creative', label: '创意写作' },
  { value: 'business', label: '商务文档' }
];

const TemplateEditor: React.FC<TemplateEditorProps> = ({
  template,
  onSave,
  onCancel
}) => {
  const [form] = Form.useForm();
  const [variables, setVariables] = useState<TemplateVariable[]>([]);
  const [showPreview, setShowPreview] = useState(false);
  const [previewContent, setPreviewContent] = useState('');
  const [editorMode, setEditorMode] = useState<'visual' | 'code'>('visual');
  const [templateContent, setTemplateContent] = useState('');

  useEffect(() => {
    if (template) {
      form.setFieldsValue({
        name: template.name,
        description: template.description,
        category: template.category,
        tags: template.tags || [],
        content: template.content,
        prompt: template.prompt,
        isPublic: template.isPublic ?? true,
        language: template.language || 'zh'
      });
      setTemplateContent(template.content || '');
      setVariables(template.variables || []);
    }
  }, [template, form]);

  // 添加变量
  const addVariable = () => {
    const newVariable: TemplateVariable = {
      name: `variable${variables.length + 1}`,
      description: '',
      type: 'text',
      required: false,
      defaultValue: ''
    };
    setVariables([...variables, newVariable]);
  };

  // 更新变量
  const updateVariable = (index: number, field: keyof TemplateVariable, value: any) => {
    const newVariables = [...variables];
    newVariables[index] = { ...newVariables[index], [field]: value };
    setVariables(newVariables);
  };

  // 删除变量
  const removeVariable = (index: number) => {
    setVariables(variables.filter((_, i) => i !== index));
  };

  // 从内容中提取变量
  const extractVariablesFromContent = () => {
    const content = form.getFieldValue('content') || templateContent;
    const regex = /\{([^}]+)\}/g;
    const matches = content.match(regex);
    
    if (!matches) {
      message.info('未在内容中发现变量占位符');
      return;
    }

    const extractedVars = matches.map((match: string) => {
      const varName = match.slice(1, -1);
      const existing = variables.find(v => v.name === varName);
      if (existing) return existing;
      
      return {
        name: varName,
        description: '',
        type: 'text' as const,
        required: true,
        defaultValue: ''
      };
    });

    // 去重
    const uniqueVars = extractedVars.filter((v, i, arr) => 
      arr.findIndex(item => item.name === v.name) === i
    );

    setVariables(uniqueVars);
    message.success(`已提取 ${uniqueVars.length} 个变量`);
  };

  // 预览模板
  const handlePreview = () => {
    const content = form.getFieldValue('content') || templateContent;
    let preview = content;
    
    // 替换变量为示例值
    variables.forEach(variable => {
      const placeholder = `{${variable.name}}`;
      const value = variable.defaultValue || `[${variable.description || variable.name}]`;
      preview = preview.replace(new RegExp(placeholder, 'g'), value);
    });
    
    setPreviewContent(preview);
    setShowPreview(true);
  };

  // 保存模板
  const handleSave = () => {
    form.validateFields().then(values => {
      const templateData = {
        ...values,
        variables,
        content: templateContent,
        id: template?.id || `template_${Date.now()}`,
        createdAt: template?.createdAt || new Date().toISOString(),
        updatedAt: new Date().toISOString(),
        usageCount: template?.usageCount || 0
      };
      
      onSave(templateData);
      message.success('模板已保存');
    });
  };

  // 复制模板代码
  const copyTemplateCode = () => {
    const templateData = {
      name: form.getFieldValue('name'),
      content: templateContent,
      variables
    };
    
    navigator.clipboard.writeText(JSON.stringify(templateData, null, 2));
    message.success('模板代码已复制到剪贴板');
  };

  return (
    <div className="template-editor">
      <Form
        form={form}
        layout="vertical"
        onFinish={handleSave}
      >
        <Tabs activeKey={editorMode} onChange={(key) => setEditorMode(key as any)}>
          <TabPane 
            tab={<span><FormOutlined /> 可视化编辑</span>} 
            key="visual"
          >
            {/* 基本信息 */}
            <Card title="基本信息" size="small" style={{ marginBottom: 16 }}>
              <Form.Item
                label="模板名称"
                name="name"
                rules={[{ required: true, message: '请输入模板名称' }]}
              >
                <Input placeholder="输入模板名称" />
              </Form.Item>

              <Row gutter={16}>
                <Col span={12}>
                  <Form.Item
                    label="模板分类"
                    name="category"
                    rules={[{ required: true, message: '请选择模板分类' }]}
                  >
                    <Select placeholder="选择分类">
                      {TEMPLATE_CATEGORIES.map(cat => (
                        <Select.Option key={cat.value} value={cat.value}>
                          {cat.label}
                        </Select.Option>
                      ))}
                    </Select>
                  </Form.Item>
                </Col>
                <Col span={12}>
                  <Form.Item
                    label="语言"
                    name="language"
                    initialValue="zh"
                  >
                    <Select>
                      <Select.Option value="zh">中文</Select.Option>
                      <Select.Option value="en">英文</Select.Option>
                      <Select.Option value="mixed">中英混合</Select.Option>
                    </Select>
                  </Form.Item>
                </Col>
              </Row>

              <Form.Item
                label="模板描述"
                name="description"
              >
                <TextArea
                  placeholder="简要描述模板的用途和特点"
                  rows={3}
                />
              </Form.Item>

              <Form.Item
                label="标签"
                name="tags"
              >
                <Select
                  mode="tags"
                  placeholder="添加标签"
                  style={{ width: '100%' }}
                />
              </Form.Item>

              <Form.Item
                label="是否公开"
                name="isPublic"
                valuePropName="checked"
                initialValue={true}
              >
                <Switch checkedChildren="公开" unCheckedChildren="私有" />
              </Form.Item>
            </Card>

            {/* 模板内容 */}
            <Card 
              title="模板内容" 
              size="small" 
              style={{ marginBottom: 16 }}
              extra={
                <Space>
                  <Button
                    size="small"
                    icon={<EyeOutlined />}
                    onClick={handlePreview}
                  >
                    预览
                  </Button>
                  <Button
                    size="small"
                    icon={<CopyOutlined />}
                    onClick={copyTemplateCode}
                  >
                    复制代码
                  </Button>
                </Space>
              }
            >
              <Alert
                message="使用 {变量名} 格式定义可替换的变量"
                type="info"
                showIcon
                style={{ marginBottom: 12 }}
              />
              
              <Form.Item
                name="content"
                rules={[{ required: true, message: '请输入模板内容' }]}
              >
                <TextArea
                  value={templateContent}
                  onChange={(e) => setTemplateContent(e.target.value)}
                  placeholder="输入模板内容，使用 {变量名} 标记可替换部分"
                  rows={12}
                  style={{ fontFamily: 'monospace' }}
                />
              </Form.Item>

              <Button
                type="dashed"
                icon={<QuestionCircleOutlined />}
                onClick={extractVariablesFromContent}
              >
                从内容中提取变量
              </Button>
            </Card>

            {/* 变量配置 */}
            <Card 
              title="变量配置" 
              size="small"
              extra={
                <Button
                  type="primary"
                  size="small"
                  icon={<PlusOutlined />}
                  onClick={addVariable}
                >
                  添加变量
                </Button>
              }
            >
              {variables.length === 0 ? (
                <Empty
                  description="暂无变量"
                  imageStyle={{ height: 60 }}
                >
                  <Button onClick={addVariable}>添加第一个变量</Button>
                </Empty>
              ) : (
                <List
                  dataSource={variables}
                  renderItem={(variable, index) => (
                    <Card size="small" style={{ marginBottom: 12 }}>
                      <Row gutter={12} align="middle">
                        <Col span={5}>
                          <Input
                            value={variable.name}
                            onChange={e => updateVariable(index, 'name', e.target.value)}
                            placeholder="变量名"
                            addonBefore="{"
                            addonAfter="}"
                          />
                        </Col>
                        <Col span={7}>
                          <Input
                            value={variable.description}
                            onChange={e => updateVariable(index, 'description', e.target.value)}
                            placeholder="变量描述"
                          />
                        </Col>
                        <Col span={4}>
                          <Select
                            value={variable.type}
                            onChange={value => updateVariable(index, 'type', value)}
                            style={{ width: '100%' }}
                          >
                            <Select.Option value="text">文本</Select.Option>
                            <Select.Option value="number">数字</Select.Option>
                            <Select.Option value="date">日期</Select.Option>
                            <Select.Option value="select">选择</Select.Option>
                            <Select.Option value="textarea">长文本</Select.Option>
                          </Select>
                        </Col>
                        <Col span={5}>
                          <Input
                            value={variable.defaultValue}
                            onChange={e => updateVariable(index, 'defaultValue', e.target.value)}
                            placeholder="默认值"
                          />
                        </Col>
                        <Col span={2}>
                          <Switch
                            checked={variable.required}
                            onChange={checked => updateVariable(index, 'required', checked)}
                            checkedChildren="必填"
                            unCheckedChildren="可选"
                          />
                        </Col>
                        <Col span={1}>
                          <Button
                            type="text"
                            danger
                            icon={<DeleteOutlined />}
                            onClick={() => removeVariable(index)}
                          />
                        </Col>
                      </Row>
                    </Card>
                  )}
                />
              )}
            </Card>
          </TabPane>

          <TabPane 
            tab={<span><CodeOutlined /> 代码编辑</span>} 
            key="code"
          >
            <Alert
              message="代码编辑模式"
              description="直接编辑模板的JSON格式，适合高级用户"
              type="warning"
              showIcon
              style={{ marginBottom: 16 }}
            />
            
            <div style={{ height: 500, border: '1px solid #d9d9d9' }}>
              <MonacoEditor
                language="json"
                value={JSON.stringify({
                  name: form.getFieldValue('name'),
                  description: form.getFieldValue('description'),
                  category: form.getFieldValue('category'),
                  content: templateContent,
                  variables,
                  tags: form.getFieldValue('tags')
                }, null, 2)}
                onChange={(value) => {
                  try {
                    const parsed = JSON.parse(value || '{}');
                    form.setFieldsValue(parsed);
                    setTemplateContent(parsed.content || '');
                    setVariables(parsed.variables || []);
                  } catch (e) {
                    // 忽略JSON解析错误
                  }
                }}
                options={{
                  minimap: { enabled: false },
                  scrollBeyondLastLine: false,
                  fontSize: 14
                }}
              />
            </div>
          </TabPane>
        </Tabs>

        <Divider />

        {/* 操作按钮 */}
        <div style={{ textAlign: 'right' }}>
          <Space>
            <Button onClick={onCancel}>
              取消
            </Button>
            <Button
              type="default"
              icon={<EyeOutlined />}
              onClick={handlePreview}
            >
              预览
            </Button>
            <Button
              type="primary"
              icon={<SaveOutlined />}
              htmlType="submit"
            >
              保存模板
            </Button>
          </Space>
        </div>
      </Form>

      {/* 预览模态框 */}
      <Modal
        title="模板预览"
        open={showPreview}
        onCancel={() => setShowPreview(false)}
        footer={null}
        width={800}
      >
        <Alert
          message="这是模板应用变量后的预览效果"
          type="info"
          showIcon
          style={{ marginBottom: 16 }}
        />
        
        <div style={{ 
          background: '#f5f5f5', 
          padding: 16, 
          borderRadius: 4,
          maxHeight: 400,
          overflow: 'auto',
          whiteSpace: 'pre-wrap'
        }}>
          {previewContent}
        </div>

        {variables.length > 0 && (
          <>
            <Divider />
            <Title level={5}>变量列表</Title>
            <Space wrap>
              {variables.map(v => (
                <Tag key={v.name} color="blue">
                  {v.name}: {v.defaultValue || v.description || '未设置'}
                </Tag>
              ))}
            </Space>
          </>
        )}
      </Modal>
    </div>
  );
};

export default TemplateEditor;